package com.example.demo.controller;

import com.example.demo.model.Comment;
import com.example.demo.service.CommentService;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("api/comments")
public class CommentController {

    private final CommentService commentService;

    // 构造函数注入 CommentService，实现依赖注入
    public CommentController(CommentService commentService) {
        this.commentService = commentService;
    }

    @GetMapping("/all")
    public ResponseEntity<List<Comment>> getAllComments() {
        List<Comment> comments = commentService.getAllComments();
        if (comments.isEmpty()) {
            return ResponseEntity.noContent().build();
        }
        return ResponseEntity.ok(comments);
    }

    // 根据ID获取论坛帖子
    @GetMapping("/{id}")
    public ResponseEntity<Comment> getCommentById(@PathVariable Long id) {
        Comment comment = commentService.getCommentById(id);
        if (comment == null) {
            return ResponseEntity.notFound().build();
        }
        return ResponseEntity.ok(comment);
    }

    // 根据用户名获取论坛帖子（示例，实际可返回列表）
    @GetMapping("/user/{userId}")
    public ResponseEntity<List<Comment>> getCommentByUsername(@PathVariable String username) {
        List<Comment> comments = commentService.getCommentByUsername(username);
        if (comments.isEmpty()) {
            return ResponseEntity.notFound().build();
        }
        return ResponseEntity.ok(comments);
    }

    // 新增论坛帖子
    @PostMapping("/create")
    public ResponseEntity<String> createComment(@RequestBody Comment comment) {
        commentService.createComment(comment);
        return ResponseEntity.ok("Comment created successfully with ID: " + comment.getId());
    }

    // 更新论坛帖子
    @PutMapping("/{id}")
    public ResponseEntity<String> updateComment(@PathVariable Long id, @RequestBody Comment comment) {
        Comment existing = commentService.getCommentById(id);
        if (existing == null) {
            return ResponseEntity.notFound().build();
        }
//        comment.setId(id); // 确保ID一致
        commentService.updateComment(comment);
        return ResponseEntity.ok("Comment updated successfully.");
    }

    // 删除论坛帖子
    @DeleteMapping("/{id}")
    public ResponseEntity<String> deleteComment(@PathVariable Long id) {
        Comment existing = commentService.getCommentById(id);
        if (existing == null) {
            return ResponseEntity.notFound().build();
        }
        commentService.deleteComment(id);
        return ResponseEntity.ok("Comment deleted successfully.");
    }
}